package com.framework.base.controller;

import com.framework.util.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 基础Controller,提供一些公共方法
 *
 * @author LeeJun
 * @create 2017-08-10 13:17
 */
public abstract class BaseController {

    public static final Logger logger = LoggerFactory.getLogger(BaseController.class);


    /**
     * 统一异常处理
     *
     * @author LeeJun
     * @time 2017-8-10 13:24
     * @version 2.0.0
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResultData runtimeExceptionHandler(RuntimeException e) {
        boolean flag = true;
        logger.error("系统异常。", e);
        Map<String, Object> paraMap = null;
        try {
            paraMap = getRequestParameters();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return ResultData.makeFailResult(e, flag, paraMap);
    }

    /**
     * 获取单个请求参数值
     *
     * @author LeeJun
     * @time 2017-8-10 13:34
     * @version 2.0.0
     */
    protected String getRequestParam(String key) {
        return this.getHttpServletRequest().getParameter(key);
    }

    /**
     * 获取参数列表
     *
     * @author LeeJun
     * @time 2017-8-10 13:34
     * @version 2.0.0
     */
    protected Map<String, Object> getRequestParameters() {
        Enumeration names = this.getHttpServletRequest().getParameterNames();
        HashMap<String, Object> map = new HashMap<>();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            map.put(name, this.getHttpServletRequest().getParameter(name));
        }
        return map;
    }

    /**
     * 获得session中的值
     *
     * @author LeeJun
     * @time 2017-8-10 13:22
     * @version 2.0.0
     */
    protected Object getSessionValue(String key) {
        return this.getHttpSession().getAttribute(key);
    }

    /**
     * 删除session中的值
     *
     * @author LeeJun
     * @time 2017-8-10 13:22
     * @version 2.0.0
     */
    protected void removeSessionValue(String key) {
        this.getHttpSession().removeAttribute(key);
    }

    /**
     * 获得当前session
     *
     * @author LeeJun
     * @time 2017-8-10 13:20
     * @version 2.0.0
     */
    protected HttpSession getHttpSession() {
        return this.getHttpServletRequest().getSession();
    }

    /**
     * 删除cookie
     */
    protected void deleteCookieByName(String cookieName) {
        Cookie[] cookies = this.getHttpServletRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                Cookie temp = new Cookie(cookie.getName(), "");
                temp.setMaxAge(0);
                this.getHttpServletResponse().addCookie(temp);
            }
        }
    }

    /**
     * 获得当前HttpServletRequest
     *
     * @author LeeJun
     * @time 2017-8-10 13:20
     * @version 2.0.0
     */
    protected HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获得当前HttpServletResponse
     *
     * @author LeeJun
     * @time 2017-8-10 13:20
     * @version 2.0.0
     */
    public static HttpServletResponse getHttpServletResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }


    protected ServletContext getServletContext() {
        return RequestContextUtils.findWebApplicationContext(this.getHttpServletRequest()).getServletContext();
    }

    public String getIPAddr(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String ip = request.getHeader("X-Forwarded-For");
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if ((ip == null) || (ip.length() == 0) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            } catch (UnknownHostException unknownhostexception) {
                logger.error("getIPAddr error.", unknownhostexception);
            }
        }
        return ip;
    }


}
